import json
import allure
import requests

class SessionUtil:
    def __init__(self):
        self.sess = requests.Session()

    def request(self, method, url, **kwargs):
        """
        封装 requests.Session().request()，并自动记录日志到 Allure
        """
        # 记录请求信息
        request_log = {
            "method": method.upper(),
            "url": url,
            "headers": kwargs.get("headers"),
            "params": kwargs.get("params"),
            "json": kwargs.get("json"),
            "data": kwargs.get("data")
        }

        # 格式化请求日志
        request_str = f"""{method.upper()} {url}
            Headers: {self._format_json(request_log['headers'])}
            Params: {self._format_json(request_log['params'])}
            Body: {self._format_json(request_log['json'] or request_log['data'])}"""

        # 自动附加到 Allure
        allure.attach(
            request_str,
            name="请求详情",
            attachment_type=allure.attachment_type.TEXT
        )

        # 发送请求
        response = self.sess.request(method, url, **kwargs)

        # 记录响应信息
        try:
            response_json = response.json()
            response_body = self._format_json(response_json)
            body_type = allure.attachment_type.JSON
        except:
            response_body = response.text
            body_type = allure.attachment_type.TEXT

        response_str = f"""响应 {response.status_code} ({response.elapsed.total_seconds() * 1000:.0f}ms)
    Headers: {self._format_json(dict(response.headers))}
    Body: {response_body}"""

        # 自动附加响应
        allure.attach(
            response_str,
            name="响应详情",
            attachment_type=body_type
        )

        return response

    def _format_json(self, data):
        if not data:
            return "None"
        try:
            return json.dumps(data, indent=2, ensure_ascii=False)
        except:
            return str(data)


session_util = SessionUtil()
